﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Traceability;
using MediatR;

namespace B.S.Database.Write.Api.Application.CommandHandler.Traceability
{
    public class TraceabilityDeleteCommandHandler : IRequestHandler<TraceabilityDeleteCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Basic_Traceability> traceabilityResotity;
        private readonly IMapper mapper;

        public TraceabilityDeleteCommandHandler(IBaseResotity<Basic_Traceability> TraceabilityResotity,IMapper mapper)
        {
            traceabilityResotity = TraceabilityResotity;
            this.mapper = mapper;
        }
        public Task<Apiresult<object>> Handle(TraceabilityDeleteCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            using (var tran = traceabilityResotity.Db.Database.BeginTransaction())
            {
                try
                {
                    var entity = traceabilityResotity.GetAll().FirstOrDefault(c => c.TraceabilityId == request.TraceabilityId);
                    if (entity == null)
                    {
                        res.Code = ApiEnums.失败;
                        res.Message = "未找到要删除的数据";
                        return Task.FromResult(res);
                    }
                    // 物理删除（真删除）
                    traceabilityResotity.Delete(entity);
                    res.Code = ApiEnums.成功;
                    res.Message = "删除成功";
                }
                catch (Exception ex)
                {
                    res.Code = ApiEnums.失败;
                    res.Message = ex.Message;
                }
            }
            return Task.FromResult(res);
        }
    }
}
